package www.bd.com.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;
import www.bd.com.dao.SpitDao;
import www.bd.com.pojo.Spit;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author Berret
 * @date 2019/4/15 14:29
 * @discription :
 */
@Service
public class SpitService {

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    public void updateThumbup(String id){
        /*Spit spit = spitDao.findById(id).get();
        spit.setThumbup(spit.getThumbup()+1);
        spitDao.save(spit);*/
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query,update,"spit");
    }

    public Page<Spit> findByParentid(String parentid, int page,int size){
        PageRequest pageRequest = PageRequest.of(page,size);
        return spitDao.findByParentid(parentid,pageRequest);
    }

    /**
     *
     */
    public List<Spit> findall(){
        return spitDao.findAll();
    }

    /**
     * 添加吐槽
     * @param spit
     */
    public void add(Spit spit){
        spit.set_id( idWorker.nextId()+"" );
        spit.setPublishtime(new Date());//发布日期
        spit.setVisits(0);//浏览量
        spit.setShare(0);//分享数
        spit.setThumbup(0);//点赞数
        spit.setComment(0);//回复数
        spit.setState("1");//状态
        if(spit.getParentid()!=null && !"".equals(spit.getParentid())){
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
            Update update = new Update();
            update.inc("comment",1);
            mongoTemplate.updateFirst(query,update,"spit");
        }
    }

    /**
     * 查询所有吐槽
     * @return
     */
    public List<Spit> spitList(){
        return spitDao.findAll();
    }

    /**
     * 根据id查询
     * @param _id
     * @return
     */
    public Spit findById(String _id){
        return spitDao.findById(_id).get();
    }

    /**
     * 修改吐槽
     */
    public void update(Spit spit){
        spitDao.save(spit);
    }

    /**
     * 根据id删除吐槽
     */
    public void delete(String _id){
        spitDao.deleteById(_id);
    }
}
